package com.clubs.coding.filter;

import com.clubs.coding.Service.UserService;
import com.clubs.coding.common.Constant;
import com.clubs.coding.model.pojo.AthAdminUser;
import com.clubs.coding.model.pojo.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/*
用户登录校验过滤器
*/
public class UserFilter implements Filter {
    public static AthAdminUser currentUser;
    private String[] excludedUris;
    @Autowired
    UserService userService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String param = filterConfig.getInitParameter("excludedUris");
        if (StringUtils.isNotBlank(param)) {
            this.excludedUris = param.split(",");
        }
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;//转化为HttpServletRequest
        HttpServletResponse response = (HttpServletResponse) servletResponse;

// 定义表示变量 并验证用户请求URI 是否包含不过滤路径
        boolean flag = false;
        for (String uri:excludedUris) {
            if (request.getRequestURI().equals(uri)){
                flag = true;
            }
        }
        if(flag){
            System.out.println("放行:"+request.getRequestURI());
         filterChain.doFilter(servletRequest, servletResponse);
        }else {

        HttpSession session = request.getSession();//拿到session
        currentUser = (AthAdminUser) session.getAttribute(Constant.ATH_CLUBS_USER);//转化为User对象
        if (currentUser == null) {//如果为空则没有登录
            PrintWriter out = new HttpServletResponseWrapper(
                    (HttpServletResponse) servletResponse).getWriter();
            out.write("{\n"
                    + "    \"status\": 10007,\n"
                    + "    \"msg\": \"NEED_SESSION\",\n"
                    + "    \"data\": null\n"
                    + "}");
            out.flush();
            out.close();
            return;
        }
        if (!flag) {
            filterChain.doFilter(servletRequest, servletResponse);
        }
        }


    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
